<script>
import axios, {Axios} from "axios";
import qs from "qs"
export default {
  name: 'home',
  mounted() {
   this.selectAll()
    },
  data() {
    return {
      homeIds:[],
      headers: { "Content-Type": "multipart/form-data" },
      home:{
        id:"",
        name:"",
        img:"",
        updateTime:"",
        status:"",
      },
      file:[],
      noneBtnImg:false,
      limitCountImg:1,
      fileList:[],
      dialogImageUrl: '',
      dialogImageVisible: false,
      dialogVisible: false,
      img:[],
    };
  },
  methods: {
    selectAll(){
      this.$http.get("home/all").then(resp=>{
        this.img = resp.data.data
      }).catch(error=>{

      })
    },
    //批量删除
    deleteByIdsHome(done){
      if (this.homeIds.length == 0) {
        this.$message({
          message: '请先选择背景',
          type: 'warning'
        });
        return

      }
      this.$confirm('是否批量删除图片？')
          .then(_ => {
            this.$http.delete("home/delete/"+this.homeIds+" ").then((resp) => {
              if (resp.data.code == 200) {
                this.$message({
                  showClose: true,
                  message: '恭喜你，删除成功',
                  type: 'success'
                });
                this.selectAll()
              }
              this.homeIds = []
              done();
            }).catch(error=>{

            })

          })

          .catch(_ => {
          });
    },
    //多选
    handleSelectionChange(val) {
      console.log(val)
      this.homeIds=[]
      for (let i = 0; i < val.length; i++) {
        this.homeIds.push(val[i].id)
      }
      console.log(this.homeIds)
    },
    //修改图片
    async UpdateHome(){
      //上传图片
      var FormDatas = new FormData()

      console.log(this.fileData)
      if (this.home.img == ""){
        FormDatas.append('file',this.fileData.file);
        const  instance = axios.create({
          withCredentials: true,
          "token":window.localStorage.getItem("token")
        });
        await instance.post("api/file-load/upload",FormDatas).then(res=>{
          this.home.img = res.data.data
          console.log(this.home.img)
        }).catch(error=>{

        });
      }
      //修改
      console.log(this.home)
        this.$http.put("home/update",this.home).then(resp=>{
          if (resp.data.code == 200){
            this.$message({
              showClose: true,
              message: '修改成功',
              type: 'success'
            });
            this.dialogVisible = false
            this.fileData={}
            this.home={}
            this.dialogImageUrl=""
            this.fileList=[]
          }
        }).catch(error=>{

        })




    },
    dealImgChange(file, fileList){
      const isJPG =
          file.raw.type === "image/jpeg" || file.raw.type === "image/png"
      const isLt2M = file.raw.size / 1024 / 1024 / 1024 / 1024 / 1024 / 1024 / 1024 / 1024 / 1024 / 1024 < 10

      if (!isLt2M) {
        this.$message.warning("上传图片大小不能超过 10M!")
        this.fileList=[]
        return
      } else if (!isJPG) {
        this.$message.warning("上传图片格式只能是jpg或png")
        this.fileList=[]
        return
      }
      this.noneBtnImg = fileList.length >= this.limitCountImg;
      this.file = file
      console.log(file)
    },
    //图片方法
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.noneBtnImg = fileList.length >= this.limitCountImg;
      this.file = []
      this.home.img=""
    },
    handlePictureCardPreview(file) {
      console.log(file)
      this.dialogImageUrl = file.url;
      this.dialogImageVisible = true;
    },
    //上传图片成功返回
    handleSuccess(response){
      console.log(response.data)
      // this.home.img=response.data
    },
    //自定义图片上传方法
    uploadFile(param){
      this.fileData = param
      // this.home.img=param.file.name
      console.log(param)
    },
    //关闭弹窗方法
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
            this.noneBtnImg=false
            this.fileData={}
            this.home={}
            this.dialogImageUrl=""
            this.fileList=[]

          })
          .catch(_ => {});
    },
    //普通删除
    deleteHome(row){
      this.$http.delete("home/delete/"+row.id+" ").then(resp=>{
        if (resp.data.code == 200) {
          this.$message({
            showClose: true,
            message: '恭喜你，删除成功',
            type: 'success'
          });
          this.selectAll()
        }
      }).catch(error=>{

      })
    },
    //编辑表单
    handleClick(row) {
      this.dialogVisible=true
      this.home = row

        this.dialogImageUrl = "api/file-load/image-download?name="+row.img+" "
        this.fileList.push({
          'url': this.dialogImageUrl
        })
      if (row.img == ""){
        this.fileList = []
        this.dialogImageUrl = []
      }

      this.noneBtnImg=false
      this.file=row
      console.log(this.home)
    }
  },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    }

}
</script>

<template>
  <div>

      <h1 style="margin-left: 2%;top: 20px;position: relative;width: 100px">主页</h1>
    <el-button type="danger" round style="position: relative;float: right;margin-right: 20px" @click="deleteByIdsHome">批量删除</el-button>

    <template>
      <el-table
          :data="img"
          style="width: 100%"
          ref="multipleTable"
          @selection-change="handleSelectionChange"
      >
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            prop="name"
            label="名称"
            width="100"
            align="center"
        >
        </el-table-column>
        <el-table-column
            prop="img"
            label="图片"
            width="800"
            align="center"
        >
          <template   slot-scope="scope" >

            <el-image :src="`api/file-load/image-download?name=${scope.row.img}`" style="width: 100%; height: 100%">
            <div slot="error" class="image-slot">
            <img src="../assets/img/error.jpg" />
            </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态"
            width="100"
            align="center"
        >
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="150">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small">编辑</el-button>
            <el-button @click="deleteHome(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
    </template>



    <!--添加form表单-->
    <el-dialog
        title="提示"
        :visible.sync="dialogVisible"
        width="30%"
        :before-close="handleClose">

      <el-form ref="form" :model="home" label-width="80px">
        <el-form-item label="名称" >
          <el-input v-model="home.name" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-tooltip :content="'当前状态: ' + home.status" placement="top">
            <el-switch
                v-model="home.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="启用"
                inactive-value="禁用"
            ></el-switch>
          </el-tooltip>
        </el-form-item>
        <!--        :auto-upload="false"-->
        <!--        api/file-load/upload-->
        <el-form-item label="图片上传">
          <el-upload
              ref="upload"
              action=""
              :headers="headers"
              :http-request="uploadFile"
              name="file"
              :file-list="fileList"
              :on-success="handleSuccess"
              :limit="limitCountImg"
              :class="{'hide': noneBtnImg}"
              :on-change="dealImgChange"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogImageVisible" v-if="dialogImageUrl != null ">
            <el-image width="100%" :src=this.dialogImageUrl alt="" />
          </el-dialog>
        </el-form-item>




        <el-form-item>
          <el-button type="primary" @click="UpdateHome">修改</el-button>
          <el-button>取消</el-button>
        </el-form-item>
      </el-form>


    </el-dialog>

  </div>
</template>

<style scoped>
::v-deep.hide .el-upload--picture-card {
  display: none;
}
</style>